package com.pmms.util;

import java.time.*;
import java.time.temporal.TemporalAdjusters;

public class TimeUtil {
    public static int getDayOfMonth(long timestamp) {
        LocalDateTime dateTime = LocalDateTime.ofInstant(
                Instant.ofEpochMilli(timestamp),
                ZoneId.systemDefault()
        );
        return dateTime.getDayOfMonth();
    }
    public static long getMidnightTimestampOfYesterday(Long timestamp) {
        LocalDateTime dateTime = LocalDateTime.ofEpochSecond(timestamp / 1000, 0, ZoneOffset.UTC);
        LocalDate yesterday = dateTime.toLocalDate().minusDays(1);
        LocalDateTime yesterdayMidnight = yesterday.atStartOfDay();
        return yesterdayMidnight.toInstant(ZoneOffset.UTC).toEpochMilli();
    }

    public static long getMidnightTimestampOfToday(Long timestamp) {
        LocalDateTime dateTime = LocalDateTime.ofEpochSecond(timestamp / 1000, 0, ZoneOffset.UTC);
        LocalDate date = dateTime.toLocalDate();
        LocalDateTime midnight = date.atStartOfDay();
        return midnight.toInstant(ZoneOffset.UTC).toEpochMilli();
    }

    public static long getMidnightTimestampOfTomorrow(Long timestamp) {
        LocalDateTime dateTime = LocalDateTime.ofEpochSecond(timestamp / 1000, 0, ZoneOffset.UTC);
        LocalDate tomorrow = dateTime.toLocalDate().plusDays(1);
        LocalDateTime tomorrowMidnight = tomorrow.atStartOfDay();
        return tomorrowMidnight.toInstant(ZoneOffset.UTC).toEpochMilli();
    }
    public static long getStartOfMonthTimestamp(Long timestamp) {
        LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.UTC);
        LocalDateTime startOfMonth = dateTime.with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0).withNano(0);

        return startOfMonth.toInstant(ZoneOffset.UTC).toEpochMilli();
    }

    public static long getEndOfMonthTimestamp(Long timestamp) {
        LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.UTC);
        LocalDateTime endOfMonth = dateTime.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59).withNano(999999999);

        return endOfMonth.toInstant(ZoneOffset.UTC).toEpochMilli();
    }
    public static double getAbsoluteDifferenceInHours(Long timestamp1, Long timestamp2) {
        // 计算两个时间戳之间的差值绝对值（毫秒）
        long differenceInMillis = Math.abs(timestamp1 - timestamp2);

        // 将差值从毫秒转换为小时
        return differenceInMillis / (1000.0 * 60 * 60);
    }

}
